package demo2;

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }

}

public class Solution {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode cur1 = l1, cur2 = l2;
        ListNode ret = new ListNode(-1);
        ListNode prev = ret;
        int t = 0;

        while(cur1 != null || cur2 != null || t != 0){
            if(cur1 != null){
                t += cur1.val;
                cur1 = cur1.next;
            }
            if(cur2 != null){
                t += cur2.val;
                cur2 = cur2.next;
            }

            prev.next = new ListNode(t % 10);
            prev = prev.next;
            t /= 10;
        }
        return ret.next;
    }

    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) { return head;}

        ListNode ret = new ListNode(-1);
        ret.next = head;
        ListNode prev = ret, cur = head, next = head.next, nnext = next.next;
        while(cur != null && next != null){
            prev.next = next;
            cur.next = nnext;
            next.next = cur;

            prev = cur;
            cur = nnext;
            if(cur != null) { next = cur.next;}
            if(next != null) { nnext = next.next;}
        }
        return ret.next;
    }
}
